/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.bpm.engine.impl.cmd;

import com.je.bpm.common.operation.OperatorEnum;
import com.je.bpm.core.model.BpmnModel;
import com.je.bpm.core.model.config.CustomEvent;
import com.je.bpm.engine.ActivitiIllegalArgumentException;
import com.je.bpm.engine.ActivitiObjectNotFoundException;
import com.je.bpm.engine.delegate.DelegateHelper;
import com.je.bpm.engine.impl.interceptor.CommandContext;
import com.je.bpm.engine.impl.persistence.entity.ExecutionEntity;
import com.je.bpm.engine.impl.persistence.entity.TaskEntity;
import com.je.bpm.engine.runtime.ProcessInstance;
import com.je.bpm.engine.task.Comment;
import com.je.bpm.engine.task.Task;
import com.je.bpm.engine.upcoming.UpcomingCommentInfoDTO;
import com.je.bpm.runtime.shared.operator.AudflagEnum;

import java.io.Serializable;
import java.util.List;
import java.util.Map;


public class DeleteProcessInstanceCmd extends NeedsActiveTaskCmd<Void> implements Serializable {

    private static final long serialVersionUID = 1L;
    protected String processInstanceId;
    protected String deleteReason;
    protected String businessKey;
    protected String prod;
    protected Map<String, Object> bean;
    protected Boolean isVoid = false;

    public DeleteProcessInstanceCmd(String processInstanceId, String deleteReason, String businessKey, String prod, Map<String, Object> bean) {
        super(false, prod, bean);
        this.processInstanceId = processInstanceId;
        this.deleteReason = deleteReason;
        this.prod = prod;
        this.bean = bean;
        this.businessKey = businessKey;
        this.isVoid = true;
    }

    public DeleteProcessInstanceCmd(String processInstanceId, String deleteReason, String prod, Map<String, Object> bean) {
        super(false, prod, bean);
        this.processInstanceId = processInstanceId;
        this.deleteReason = deleteReason;
        this.isVoid = false;
    }

    @Override
    public Void execute(CommandContext commandContext, TaskEntity taskEntity) {
        if (processInstanceId == null) {
            throw new ActivitiIllegalArgumentException("processInstanceId is null");
        }
        ExecutionEntity processInstanceEntity = commandContext.getExecutionEntityManager().findById(processInstanceId);
        String beanId = processInstanceEntity.getBusinessKey();
        if (!isVoid) {
            commandContext.getExecutionEntityManager().deleteProcessInstance(processInstanceEntity.getProcessInstanceId(), deleteReason, false);
            return null;
        }
        List<Task> list = commandContext.getProcessEngineConfiguration().getTaskService().createTaskQuery().processInstanceId(processInstanceId).list();
        String pdid = "";
        StringBuffer nodeIds = new StringBuffer();
        StringBuffer nodeNames = new StringBuffer();
        for (Task task : list) {
            pdid = task.getProcessDefinitionId();
            if (nodeIds.length() > 0) {
                nodeIds.append(",");
                nodeNames.append(",");
            }
            nodeIds.append(task.getId());
            nodeNames.append(task.getName());
            commandContext.getProcessEngineConfiguration().getTaskService().addComment(task.getId(), processInstanceId,
                    Comment.USER_COMMENT, deleteReason);
            commandContext.getProcessEngineConfiguration().getTaskService().addComment(task.getId(), processInstanceId,
                    Comment.NODE_TYPE, "审批作废");
        }

        BpmnModel bpmnModel = commandContext.getProcessEngineConfiguration().getRepositoryService().getBpmnModel(pdid);
        UpcomingCommentInfoDTO upcomingInfo = DelegateHelper.buildUpcomingInfo(null, deleteReason, SubmitTypeEnum.INVALID, beanId
                , "", null);
        commandContext.getProcessEngineConfiguration().getActivitiUpcomingRun().completeUpcoming(upcomingInfo);
        if (processInstanceEntity == null) {
            throw new ActivitiObjectNotFoundException("No process instance found for id '" + processInstanceId + "'", ProcessInstance.class);
        }

        commandContext.addAttribute("processType","void");
        //执行自定义流程、节点策略
        commandContext.getProcessEngineConfiguration().getProcessInstanceHelper().invokeEvent
                (bpmnModel.getMainProcess().getCustomEventListeners(), nodeNames.toString(),
                        nodeIds.toString(), "",
                        CustomEvent.CustomEventEnum.PROCESS_VOID, commandContext, deleteReason, "", OperatorEnum.PROCESS_INVALID_OPERATOR);
        commandContext.getProcessEngineConfiguration().getProcessInstanceHelper().updateBeanInfo
                (bpmnModel.getMainProcess().getProcessConfig(), businessKey,
                        AudflagEnum.SUSPEND.toString(), commandContext);

        commandContext.getExecutionEntityManager().deleteProcessInstance(processInstanceEntity.getProcessInstanceId(), deleteReason, false);
        return null;
    }

}
